#!/usr/bin/env python
#
#       Analyses.py
#       
#       Copyright 2009 Brandon Invergo <brandon@brandoninvergo.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

import sys

try:
    import pygtk
    #tell pyGTK, if possible, that we want GTKv2
    pygtk.require("2.0")
except:
    #Some distributions come with GTK2, but not pyGTK
    pass

try:
    import gtk
    import gtk.glade
    
except:
    print "You need to install pyGTK or GTKv2 ",
    print "or set your PYTHONPATH correctly."
    print "try: export PYTHONPATH=",
    print "/usr/local/lib/python2.2/site-packages/"
    sys.exit(1)
    
from gobject import TYPE_STRING, TYPE_PYOBJECT
import Error_dialog
from MajeRe_Engine import REngException
from libraries import stats

    
class Analyses_tab:   
    def on_analyses_cursor_changed(self, treeview):
        cursor = self.a_treeview.get_cursor()[0]
        if cursor == None:
            self.execute_button.set_sensitive(False)
        else:
            self.execute_button.set_sensitive(True)
    
    def on_analysis_activated(self, view, path, column):
        self.on_execute_button(view)
    
    def on_execute_button(self, widget):
        cursor = self.a_treeview.get_cursor()[0]
        if cursor == None:
            return
        a_iter = self.a_treestore.get_iter(cursor)
        if self.a_treestore.iter_depth(a_iter) == 0:
            return
        analysis_func = self.a_treestore.get_value(a_iter, 2)
        analysis_lib = self.a_treestore.get_value(a_iter, 3) 
        
        dg_cursor = self.dg_treeview.get_cursor()[0]
        parent_iter = self.dg_treestore.get_iter(dg_cursor)
        data_group = self.dg_treestore.get_value(parent_iter, 4)
        command = analysis_func(data_group)
        if command.get("main") == "":
            return
        
        precommand = command.get("pre")
        try:
            self.main_window.do_R_command(precommand, True)
        except REngException, error_msg:
            self.error.show_error("R engine error", error_msg.parameter)
            return
        
        maincommand = command.get("main")
        try:
            res = self.main_window.do_R_command(maincommand, True)
        except REngException, error_msg:
            self.error.show_error("R engine error", error_msg.parameter)
            return
        else:
            result = ""
            for line in res:
                result = result + line
            analysis_name = self.a_treestore.get_value(a_iter, 0)
            if data_group.has_result(analysis_name):
                data_group.edit_result(analysis_name, command = command, results_text = result)
            else:
                data_group.add_result(analysis_name, command, result)
        
        postcommand = command.get("post")
        try:
            self.main_window.do_R_command(postcommand, True)
        except REngException, error_msg:
            self.error.show_error("R engine error", error_msg.parameter)
            return
            
        self.main_window.results.update_results(data_group)
        self.main_window.project_tab.set_current_page(2)
            
    def on_dg_cursor_changed(self, treeview):
        cursor = self.dg_treeview.get_cursor()[0]
        dg_iter = self.dg_treestore.get_iter(cursor)
        data_group = self.dg_treestore.get_value(dg_iter, 4)
        self.a_treestore.clear()
        for library in self.main_window.available_libraries:
            if library.library_type == "analyses":
                compatable_funcs = library.compatible_funcs(data_group)
                library_description = library.library_description
                parent_iter = self.a_treestore.append(None, [library_description, "", None, None])
                for func in compatable_funcs:
                    func.append(library)
                    self.a_treestore.append(parent_iter, func)   
        self.a_treeview.expand_all()
        self.on_analyses_cursor_changed(self.a_treeview)
     
    def dg_select_func(self, path):
        if len(path) == 1:
            return True
        else:
            parent_path = (path[0],)
            self.dg_treeview.set_cursor(parent_path)
            return False
            
    def a_select_func(self, path):
        if len(path) == 2:
            return True
        else:
            path = (path[0], 0)
            self.a_treeview.set_cursor(path)
            return False
            
    def a_namecol_func(self, column, cell, model, iter):
        if model.iter_parent(iter) == None:
            name = model.get_value(iter, 0)
            cell.set_property('markup', "<b>" + name + "</b>")
        return
    
    def __init__(self, parent_window, glade_gui):
        self.main_window = parent_window
        self.glade_gui = glade_gui
        self.error = Error_dialog.Error_dialog()
        
        callbacks = {"on_analyses_cursor_changed":self.on_analyses_cursor_changed,\
            "on_analyses_dg_cursor_changed" : self.on_dg_cursor_changed,\
            "on_Analyses_execute" : self.on_execute_button, \
            "on_analyses_row_activated": self.on_analysis_activated}
        self.glade_gui.signal_autoconnect(callbacks)
        
        self.execute_button = self.glade_gui.get_widget("Analyses_execute")
        
        self.dg_treestore = self.main_window.data.dg_treestore
        self.dg_treeview = self.glade_gui.get_widget("Analyses_dg_treeview")
        self.dg_treeview.set_model(self.dg_treestore)
        dg_namecol = gtk.TreeViewColumn("Name")
        self.dg_treeview.append_column(dg_namecol)
        dg_namecell = gtk.CellRendererText()
        dg_namecol.pack_start(dg_namecell, True)

        dg_idcol = gtk.TreeViewColumn("ID")
        self.dg_treeview.append_column(dg_idcol)
        dg_idcell = gtk.CellRendererText()
        dg_idcol.pack_start(dg_idcell, True)

        dg_typecol = gtk.TreeViewColumn("Role")
        self.dg_treeview.append_column(dg_typecol)
        dg_typecell = gtk.CellRendererText()
        dg_typecol.pack_start(dg_typecell, True)
                
        dg_ncol = gtk.TreeViewColumn("n")
        self.dg_treeview.append_column(dg_ncol)
        dg_ncell = gtk.CellRendererText()
        dg_ncol.pack_start(dg_ncell, True)
        dg_namecol.add_attribute(dg_namecell, 'text', 0)
        dg_idcol.add_attribute(dg_idcell, 'text', 1)
        dg_typecol.add_attribute(dg_typecell, 'text', 2)
        dg_ncol.add_attribute(dg_ncell, 'text', 3)
        
        dg_selection = self.dg_treeview.get_selection()
        dg_selection.set_mode(gtk.SELECTION_SINGLE)
        dg_selection.set_select_function(self.dg_select_func)        
        
        self.a_treestore = gtk.TreeStore(TYPE_STRING, TYPE_STRING, TYPE_PYOBJECT, TYPE_PYOBJECT)
        self.a_treeview = self.glade_gui.get_widget("Analyses_treeview")
        self.a_treeview.set_model(self.a_treestore)
        
        a_namecol = gtk.TreeViewColumn("Name")
        self.a_treeview.append_column(a_namecol)
        a_namecell = gtk.CellRendererText()
        a_namecol.pack_start(a_namecell, True)
        a_namecol.set_cell_data_func(a_namecell, self.a_namecol_func)
        
        a_desccol = gtk.TreeViewColumn("Description")
        self.a_treeview.append_column(a_desccol)
        a_desccell = gtk.CellRendererText()
        a_desccol.pack_start(a_desccell, True)
        
        a_namecol.add_attribute(a_namecell, 'text', 0)
        a_desccol.add_attribute(a_desccell, 'text', 1)
        a_selection = self.a_treeview.get_selection()
        a_selection.set_mode(gtk.SELECTION_SINGLE)
        a_selection.set_select_function(self.a_select_func)  

        
